<?php

namespace App\Http\Requests\Staff;

use App\Http\Models\App\App;
use App\Http\Models\App\AppAuth;
use App\Http\Models\App\AppGroup;
use App\Http\Models\App\AppGroupAuthRelation;
use App\Http\Models\Staff\StaffAppGroupRelation;
use App\Http\Models\Staff\StaffAppRelation;
use App\Http\Requests\Common\BaseRequest as Request;
use Cache;

class StaffRequest extends Request
{
    //
    public function center()
    {
        dd('hello staff');
    }
    //
    public function auth()
    {
        //动态验证发送过来的数据
        $rules = [
            "host"   => "required",
            "key"    => "required|min:2|max:80",
            "secret" => "required|min:2|max:80",
            "ticket" => "required|min:2|max:80",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
        );
        $attributes = array(
            "host"   => "应用域名",
            "key"    => "应用签名",
            "secret" => "应用秘钥",
            "ticket" => "登录返回ticket",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        // Validate Service
        $cache_key = md5($data['host'] . $data['key'] . $data['secret']);
        $app_id    = Cache::remember($cache_key, 15, function () use ($data) {
            return \App\Http\Models\App\App::where('deleted_at', 0)->where('host', $data['host'])->where('key', $data['key'])->where('secret', $data['secret'])->pluck('id');
        });
        if (is_null($app_id)) {
            return self::_json([], 1, 'app_key|app_secret|app_host错误！');
        }
        //
        $ticket = Cache::tags('ticket')->get($data['ticket']);
        if (is_null($ticket)) {
            return self::_json([], -1, 'ticket无效!');
        }
        //
        $detail = Cache::tags('staff')->get($ticket['ticket']);
        if (!is_null($detail)) {
            $detail = self::Detail($app_id, $ticket['staff_id'], $ticket['ticket']);
            Cache::tags('staff')->put($ticket['ticket'], $detail, 120);
        }
        return self::_json($detail, 0, '获取用户权限成功');
    }
    //
    public function auth_check()
    {
        //动态验证发送过来的数据
        $rules = [
            "app_id"   => "required|exists:app,id",
            "staff_id" => "required|exists:staff,id",
            "ticket"   => "required|min:2|max:80",
            "uri"      => "required|exists:app_auth,uri",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "exists"   => ":attribute不存在",
        );
        $attributes = array(
            "app_id"   => "应用ID",
            "staff_id" => "员工ID",
            "ticket"   => "用户凭证",
            "uri"      => "权限路由",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //
        $ticket = Cache::tags('ticket')->get($data['ticket']);
        if (is_null($ticket)) {
            return self::_json([], -1, 'ticket无效!');
        }
        //1-检查应用是否已禁用
        $appId = App::where('id', $data['app_id'])->where('status', 1)->pluck('id');
        if (is_null($appId)) {
            return self::_json(['result' => false, 'info' => '应用已禁用!']);
        }
        $appRelationId = StaffAppRelation::where('app_id', $data['app_id'])
            ->where('staff_id', $data['staff_id'])
            ->where('status', 1)
            ->pluck('id');
        if (is_null($appRelationId)) {
            return self::_json(['result' => false, 'info' => '用户应用关联已禁用!']);
        }
        //2-检查权限是否已禁用
        $authId = AppAuth::where('uri', $data['uri'])->where('status', 1)->pluck('id');
        if (is_null($authId)) {
            return self::_json(['result' => false, 'info' => '应用权限已禁用!']);
        }
        //3-检查用户关联角色组是否已禁用
        $groupId = StaffAppGroupRelation::where('staff_id', $data['staff_id'])
            ->where('app_id', $data['app_id'])
            ->pluck('group_id');
        $group_id = AppGroup::where('id', $groupId)->where('status', 1)->pluck('id');
        if (is_null($group_id)) {
            return self::_json(['result' => false, 'info' => '应用角色组已禁用!']);
        }
        //4-检查用户用户角色组关联的权限是否禁用
        $auth_id = AppGroupAuthRelation::where('group_id', $groupId)
            ->where('auth_id', $authId)
            ->where('status', 1)
            ->pluck('id');
        if (is_null($auth_id)) {
            return self::_json(['result' => false, 'info' => '用户权限已禁用!']);
        }
        return self::_json(['result' => true, 'info' => '用户权限正常!']);
    }
    //
    public static function Detail($app_id = 0, $staff_id = 0, $ticket = '')
    {
        //
        $staff  = \App\Http\Models\Staff\Staff::where('id', $staff_id)->first();
        $detail = [
            'id'            => $staff->id,
            'ticket'        => $ticket,
            'name'          => $staff->name,
            'mobile'        => $staff->mobile,
            'account'       => $staff->account,
            'email'         => $staff->email,
            'station_id'    => $staff->station_id,
            'app_info'      => [], //用户关联的信息
            'dept_info'     => [], //部门信息
            'post_info'     => [], //职称信息
            'group_info'    => [], //角色组信息
            'extra_param'   => [], //额外参数
            'station_param' => [], //售票专用参数
            'auth_list'     => [], //权限列表
        ];
        //应用
        $app = \App\Http\Models\App\App::where('id', $app_id)
            ->select('id', 'name', 'host', 'key', 'secret', 'desc', 'status')
            ->first();
        $detail['app_info'] = self::_toArray($app);
        //部门
        $dept = \App\Http\Models\Staff\StaffDept::where('id', $staff->dept_id)
            ->select('id', 'name')
            ->first();
        $detail['dept_info'] = self::_toArray($dept);
        //职位
        $post = \App\Http\Models\Staff\StaffPost::where('id', $staff->post_id)
            ->select('id', 'name', 'code')
            ->first();
        $detail['post_info'] = self::_toArray($post);
        //用户关联app的角色组
        $group_id = \App\Http\Models\Staff\StaffAppGroupRelation::where('app_id', $app_id)
            ->where('staff_id', $staff_id)
            ->pluck('group_id');
        $group = \App\Http\Models\App\AppGroup::where('id', $group_id)
            ->select('id', 'name', 'status')
            ->first();
        $detail['group_info'] = self::_toArray($group);
        //角色组关联的额外参数
        $extra = \App\Http\Models\App\AppGroupExtra::where('group_id', $group_id)
            ->select('id', 'name', 'key', 'value', 'desc')
            ->get();
        $detail['extra_param'] = self::_toArray($extra);
        //补充售票系统专用参数
        //$model  = new \App\Http\Models\Station\SysUser($staff->station_id);
        // $remote = $model->where('LoginID', $staff->account)
        //     ->select('ID', 'LoginID', 'UserName', 'OpAddress', 'OpStation')
        //     ->first();
        $remote = [];
        $stationParam = [];
        if ($remote) {
            $stationParam = [
                'Operator_ID'      => $remote->ID,
                'Operator_Account' => $remote->LoginID,
                'Operator_Name'    => $remote->UserName,
                'OpStation_ID'     => $remote->OpAddress,
                'OpStation_SYS_ID' => $remote->OpStation,
                'OpStation_DB_ID'  => $staff->station_id,
            ];
        }
        $detail['station_param'] = $stationParam;
        //角色组关联的权限
        if ($app->status && $group->status) {
            $auths = \App\Http\Models\App\AppGroupAuthRelation::join('app_auth', function ($join) {
                $join->on('app_group_auth_relation.auth_id', '=', 'app_auth.id');
            })
                ->where('app_group_auth_relation.group_id', $group_id)
                ->where('app_auth.status', 1)
                ->select('app_auth.id', 'app_auth.parent_id', 'app_auth.name', 'app_auth.uri', 'app_auth.css', 'app_auth.is_show', 'app_auth.desc', 'app_auth.weight')
                ->orderBy('app_auth.id', 'asc')
                ->orderBy('app_auth.weight', 'desc')
                ->get();
            $detail['auth_list'] = self::_toArray($auths);
        }
        return $detail;
    }
}
